package com.lc202310;

/**
 * Description:
 *
 * @Create 2023/10/14 21:00
 * @Version 1.0
 */
public class Solution34 {
    public static int[] searchRange(int[] nums, int target) {
        int length = nums.length;
        if (length == 0) {
            return new int[]{-1, -1};
        }
        int start = getIndex(nums, target, true, 0);
        if (start == -1) {
            return new int[]{-1, -1};
        }
        int end = getIndex(nums, target, false, start);
        return new int[]{start, end};
    }

    private static int getIndex(int[] nums, int target, boolean isFist, int start) {
        int ans = -1;
        int left = start;
        int right = nums.length - 1;
        while (left < right) {
            int mid = (left + right) / 2;
            if (mid > nums.length - 1) {
                break;
            }
            if (nums[mid] > target) {
                right = mid - 1;
                continue;
            }
            if (nums[mid] < target) {
                left = mid + 1;
                continue;
            }
            ans = mid;
            if (isFist) {
                right = mid - 1;
                continue;
            }
            left = mid + 1;
        }
        if (nums[left] == target) {
            return left;
        }
        return ans;
    }

    public static void main(String[] args) {
        int[] ints = searchRange(new int[]{5, 7, 7, 8, 8, 10}, 8);
        for (int anInt : ints) {
            System.out.println(anInt);
        }
    }
}
